package com.tbl.modules.wms.service.Impl.baseinfo;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.tbl.common.utils.DateUtils;
import com.tbl.common.utils.PageTbl;
import com.tbl.common.utils.PageUtils;
import com.tbl.common.utils.StringUtils;
import com.tbl.modules.platform.util.DeriveExcel;
import com.tbl.modules.wms.constant.EmumConstant;
import com.tbl.modules.wms.dao.baseinfo.CarDAO;
import com.tbl.modules.wms.dao.baseinfo.WarehouseDAO;
import com.tbl.modules.wms.entity.baseinfo.Car;
import com.tbl.modules.wms.service.baseinfo.CarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 行车
 * @author 70486
 */
@Service
public class CarServiceImpl extends ServiceImpl<CarDAO, Car> implements CarService {

    /**
     * 行车
     */
    @Autowired
    private CarDAO carDAO;
    /**
     * 仓库
     */
    @Autowired
    private WarehouseDAO warehouseDAO;

    /**
     * 获取行车数据列表
     * @param pageTbl
     * @param map
     * @return PageUtils
     */
    @Override
    public PageUtils getPageList(PageTbl pageTbl, Map<String, Object> map) {
    	if(map.get("code")!=null) {
            map.put("code", map.get("code").toString().toUpperCase());
        }
        String sortOrder = pageTbl.getSortorder();
        String sortName = pageTbl.getSortname();
        if (StringUtils.isEmptyString(sortName)) {
            sortName = "id";
        }
        if (StringUtils.isEmptyString(sortOrder)) {
            sortOrder = "desc";
        }
        Page page = new Page(pageTbl.getPageno(), pageTbl.getPagesize(), sortName, "asc".equalsIgnoreCase(sortOrder));
        return new PageUtils(page.setRecords(carDAO.getPageList(page, map)));
    }

    /**
     * 获取导出Excel列表
     * @param ids 多选条数
     * @param queryCode 行车编号
     * @param queryFactoryCode 厂区编码
     * @param queryWarehouse 仓库编码
     * @param factoryList 厂区列表
     * @return List<Car> 行车列表
     */
    @Override
    public List<Car> getExcelList(String ids, String queryCode, String queryFactoryCode, String queryWarehouse, List<String> factoryList) {
        Map<String, Object> map = new HashMap<>();
        map.put("ids", StringUtils.stringToInt(ids));
    	map.put("code", queryCode);
    	map.put("factoryCode", queryFactoryCode);
        map.put("warehouse", StringUtils.isNotEmpty(queryWarehouse)?Long.parseLong(queryWarehouse):null);
        map.put("factoryList", factoryList);
        return carDAO.getExcelList(map);
    }

    /**
     * 根据主键查询行车信息
     * @param id 行车主键
     * @param factoryCode 厂区编码
     * @return Car 行车信息
     */
    @Override
    public Car findCarById(Long id,String factoryCode) {
        return id == null || id==0L ? new Car() : carDAO.findCarById(id,factoryCode);
    }

    /**
     * 获取仓库列表信息
     * @param pageTbl 分页工具页面类
     * @param map 参数条件
     * @return PageUtils
     */
    @Override
    public PageUtils getPageWarehouseList(PageTbl pageTbl, Map<String, Object> map) {
        String sortName = pageTbl.getSortname();
        String sortOrder = pageTbl.getSortorder();
        if (StringUtils.isEmptyString(sortName)) {
            sortName = "id";
        }
        if (StringUtils.isEmptyString(sortOrder)) {
            sortOrder = "desc";
        }
        Page page = new Page(pageTbl.getPageno(), pageTbl.getPagesize(), sortName, "asc".equalsIgnoreCase(sortOrder));
        return new PageUtils(page.setRecords(warehouseDAO.getPageWarehouseList(page, map)));
    }

    /**
     * 保存行车信息
     * @param car 行车
     * @return boolean
     */
    @Override
    public boolean saveCar(Car car) {
        car.setWarehouseCode(warehouseDAO.selectById(car.getWarehouse()).getCode());
        if (car.getId() == null) {
            Long maxValue = carDAO.selectMaxCarId();
            maxValue = maxValue==null ? Long.valueOf(EmumConstant.carState.OUTSTORAGING.getCode()) : maxValue +
                    EmumConstant.carState.OUTSTORAGING.getCode();
            car.setCode("HC" + maxValue);
            car.setState(Long.valueOf(EmumConstant.carState.UNUSED.getCode()));
        }
        return this.insertOrUpdate(car);
    }

    /**
     * 删除行车
     * @param ids 行车主键
     * @return boolean
     */
    @Override
    public boolean deleteCars(String ids) {
        return this.deleteBatchIds(StringUtils.stringToList(ids));
    }

    /**
     * 根据行车编码获取小车
     * @param code 行车编码
     * @return car 行车实体
     */
    @Override
    public Car findCarByCode(String code) {
        List<Car> list = carDAO.selectList(new EntityWrapper<Car>().eq("CODE",code));
        return list.size() > 0 ? list.get(0) : null;
    }
    
    /**
     * 功能描述：获取所有的仓库区域
     * @return Map<String,Object>
     */
    @Override
    public List<Map<String,Object>> selectWarehouseArea(){
    	return carDAO.selectWarehouseArea();
    }

    /**
     * 更新行车状态
     * @param carCode 行车编码
     * @param missionShelf 目标库位
     * @param state 行车状态
     * @return boolean
     */
    @Override
    public Boolean updateCarByCode(String carCode, String missionShelf, Long state){
        Car car = null;
        boolean result = false;
        if (org.apache.commons.lang3.StringUtils.isNotBlank(carCode)){
            car = carDAO.selectOne(new Car() {{
                setCode(carCode);
            }});
        }
        if(car!=null) {
            car.setState(state);
            car.setMission(missionShelf);
            result = carDAO.updateById(car) > 0;
        }

        return result;
    }

    /**
     * 行吊台账查询数据列表
     * @param pageTbl
     * @param params
     * @return PageUtils
     */
    @Override
    public PageUtils getHangCarList(PageTbl pageTbl, Map<String, Object> params) {
        Page page = new Page(pageTbl.getPageno(), pageTbl.getPagesize(), pageTbl.getSortname(),
                "asc".equalsIgnoreCase(pageTbl.getSortorder()));
        return new PageUtils(page.setRecords(carDAO.getHangCarList(page, params)));
    }

    /**
     * 获取导出Excel列表
     * @param params
     * @return Map<String,Object>
     */
    @Override
    public List<Map<String,Object>> getAllHangCarLists(Map<String, Object> params) {
        return carDAO.getHangCarExcelList(params);
    }

    /**
     * 出库台账表导出Excel
     * @param response
     * @param path 路径
     * @param list
     * @param excelIndexArray
     */
    @Override
    public void toHangCarerExcel(HttpServletResponse response, String path, List<Map<String,Object>> list, String [] excelIndexArray) {
        try {
            String sheetName = "行车工台账" + "(" + DateUtils.getDay() + ")";
            if (path != null && !"".equals(path)) {
                sheetName = sheetName + ".xls";
            } else {
                response.setHeader("Content-Type", "application/force-download");
                response.setHeader("Content-Type", "application/vnd.ms-excel");
                response.setCharacterEncoding("UTF-8");
                response.setHeader("Expires", "0");
                response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
                response.setHeader("Pragma", "public");
                response.setHeader("Content-disposition", "attachment;filename=" + new String(sheetName.getBytes("gbk"),
                        "ISO8859-1") + ".xls");
            }
            Map<String, String> mapFields = new LinkedHashMap<>();
            if (excelIndexArray.length==1&&"".equals(excelIndexArray[0])) {
                mapFields.put("QACODE", "质保单号");
                mapFields.put("BATCH_NO", "批次号");
                mapFields.put("MATERIALCODE", "物料编号");
                mapFields.put("MATERIALNAME", "物料名称");
                mapFields.put("FACTORYNAME", "厂区");
                mapFields.put("WAREHOUSENAME", "仓库");
                mapFields.put("SHELFCODE", "库位");
                mapFields.put("HANGTIMESTR", "吊装时间");
                mapFields.put("NAME", "行车工");
            }else {
                for (String s : excelIndexArray) {
                    if ("2".equals(s)) {
                        mapFields.put("QACODE", "质保单号");
                    } else if ("3".equals(s)) {
                        mapFields.put("BATCHNO", "批次号");
                    } else if ("4".equals(s)) {
                        mapFields.put("MATERIALCODE", "物料编号");
                    } else if ("5".equals(s)) {
                        mapFields.put("MATERIALNAME", "物料名称");
                    } else if ("6".equals(s)) {
                        mapFields.put("FACTORYNAME", "厂区");
                    } else if ("7".equals(s)) {
                        mapFields.put("WAREHOUSENAME", "仓库");
                    } else if ("8".equals(s)) {
                        mapFields.put("SHELFCODE", "库位");
                    } else if ("9".equals(s)) {
                        mapFields.put("HANGTIMESTR", "吊装时间");
                    } else if ("10".equals(s)) {
                        mapFields.put("NAME", "行车工");
                    }
                }
            }

            DeriveExcel.exportMapExcel(sheetName, list, mapFields, response, path);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
